package com.xiaolin.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName MySocketServer
 * @Description socket 服务端 -支持多线程
 * @Detail 服务端应先于客户端开启
 * @Author MyPC
 * @Date 2020/12/1
 * @Version 1.0
 */
public class MyMultiThreadSocketServer {
    public static void main(String[] args) throws IOException {
        // 服务端套接字的监听端口
        int port=7000;
        int clientNo=1;
        // 在端口上创建一个服务器套接字
        ServerSocket serverSocket=new ServerSocket(port);
        // 创建一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true){
            // 监听来自客户端的连接
            Socket server = serverSocket.accept();
            executorService.execute(new SingleSocketServer(server,clientNo));
            clientNo++;
        }
    }
}

class SingleSocketServer implements Runnable{
    private Socket server;
    private int clientNo;
    public SingleSocketServer(Socket socket,int clientNo){
        this.server=socket;
        this.clientNo=clientNo;
    }

    @Override
    public void run() {
        // 数据输入流
        DataInputStream dataInputStream= null;
        try {
            dataInputStream = new DataInputStream(new BufferedInputStream(server.getInputStream()));
            // 数据输出流
            DataOutputStream dataOutputStream=new DataOutputStream(new BufferedOutputStream(server.getOutputStream()));
            do{
                // 从客户端读取数据
                double accept = dataInputStream.readDouble();
                System.out.println("从客户端"+clientNo+"收到了数据："+accept);
                // 计算结果
                double result=accept*accept;
                // 输出结果到客户端
                dataOutputStream.writeDouble(result);
                // 输出是刷新
                dataOutputStream.flush();
            }while (dataInputStream.readInt() != 0);
            System.out.println("结束通信！");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭监听
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
